package br.edu.catolica.sadbc.manager;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.persistence.Query;

import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.framework.EntityQuery;

import br.edu.catolica.sadbc.core.exception.BusinessObjectException;
import br.edu.catolica.sadbc.core.manager.AbstractCrudManager;
import br.edu.catolica.sadbc.core.util.DataUtil;
import br.edu.catolica.sadbc.entity.Saida;
import br.edu.catolica.sadbc.entity.Usuario;
import br.edu.catolica.sadbc.entity.enums.SimNao;
import br.edu.catolica.sadbc.entity.filter.SaidaSearchFilter;

/**
 * 
 * @author robert.resende
 *
 */
@AutoCreate
@Name(value = "saidaManager")
public class SaidaManager extends AbstractCrudManager<Saida> {
	
	private static final String ejbql = "select obj from Saida obj";
	@SuppressWarnings("unused")
	private static final String operator = "or";
	private String[] restriction = {
			" obj.docente.id = #{saidaSearchFilter.docente.id} ",
			" obj.tipoSaida = #{saidaSearchFilter.tipoSaida} ",
			" obj.ativa = #{saidaSearchFilter.ativa} ",
			" obj.semestreSaida = #{saidaSearchFilter.semestreSaida} ",
			" obj.anoSaida >= #{saidaSearchFilter.anoInicio} ",
			" obj.anoSaida <= #{saidaSearchFilter.anoFim} "};

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<Saida> pesquisar(SaidaSearchFilter saidaSearchFilter) {
		List<Saida> lista = new ArrayList<Saida>();
		EntityQuery entityQuery = new EntityQuery();
		entityQuery.setEjbql(ejbql);
		entityQuery.setRestrictionExpressionStrings(Arrays.asList(restriction));
		lista = entityQuery.getResultList();
		log.info("Lista vazia: " + lista.isEmpty());
		log.info("Tamanho da lista: " + lista.size());
		return lista;
	}
	
	@Override
	public String salvar(Saida saida) throws BusinessObjectException {
		doPreInsert(saida);
		return super.salvar(saida);
	}
	
	private void doPreInsert(Saida saida) {
		//FIXME - mudar para inteiro
		saida.setAtiva(SimNao.SIM.getValue());
		saida.setDataCadastro(DataUtil.getInstance().getDataAtual());
	}

	public String excluir(Saida saida) throws BusinessObjectException {
		doPreExclude(saida);
		return super.update(saida);
	}

	private void doPreExclude(Saida saida) {
		//FIXME - mudar para inteiro
		saida.setAtiva(SimNao.NAO.getValue());
		saida.setDataAtualizacao(DataUtil.getInstance().getDataAtual());
	}

	@SuppressWarnings("unchecked")
	public List<Saida> buscarSaidasAgendadas(Usuario usuarioSession) {
		List<Saida> lista = new ArrayList<Saida>();
		Query query = this.entityManager.createQuery("select obj from Saida obj where obj.docente.id = :id order by obj.anoSaida asc");
		query.setParameter("id", usuarioSession.getDocente().getId());
		lista = query.getResultList();
		return lista;
	}

}
